package com.ushine.web.base.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ushine.web.base.mapper.OrgMapper;
import com.ushine.web.base.model.system.OrgDO;
import com.ushine.web.base.model.system.UserDO;
import com.ushine.web.base.service.IOrgService;
import com.ushine.web.component.authority.annotation.DataPermissionFilter;
import com.ushine.web.component.authority.config.DataFilterThreadLocal;
import com.ushine.web.component.contant.BusinessConstant;
import com.ushine.web.component.page.PageRequestQuery;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @Author: yls
 * @Date: 2022/03/01 09:43
 * @Description: 组织数据层
 * @Version 1.0
 */
@Service
public class OrgServiceImpl extends ServiceImpl<OrgMapper, OrgDO> implements IOrgService {

    @Override
    public Boolean insertOrg(OrgDO org) {
        return save(org);
    }

    @Override
    @Transactional(readOnly = true)
    public Optional<OrgDO> getOrgById(Long id) {
        return Optional.of(getById(id));
    }

    @Override
    public Optional<OrgDO> getOrgByOrgName(String orgName) {
        LambdaQueryWrapper<OrgDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(OrgDO::getOrgName, orgName).last(BusinessConstant.LIMIT_ONE);
        return Optional.ofNullable(getOne(lambdaQueryWrapper));
    }

    @Override
    @Transactional(readOnly = true)
    @DataPermissionFilter(function = "org:select:listByIds")
    public List<OrgDO> listOrgs(Set<Long> ids) {
        return listByIds(ids);
    }

    @Override
    @Transactional(readOnly = true)
    @DataPermissionFilter(function = "org:select:listByIds")
    public List<OrgDO> listOrgsByThread(UserDO user, Set<Long> ids) {
        DataFilterThreadLocal.setUser(user);
        return listByIds(ids);
    }

    @Override
    public Page<OrgDO> listOrgByPage(PageRequestQuery pageRequestQuery) {
        Page<OrgDO> page = new Page<>(pageRequestQuery.getPageNum(), pageRequestQuery.getPageSize());
        LambdaQueryWrapper<OrgDO> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        return page(page, lambdaQueryWrapper);
    }
}
